package com.spyx.order.service.impl;

import com.atyx.spyx.enums.*;
import com.atyx.spyx.model.activity.ActivityRule;
import com.atyx.spyx.model.activity.CouponInfo;
import com.atyx.spyx.model.order.CartInfo;
import com.atyx.spyx.model.order.OrderInfo;
import com.atyx.spyx.model.order.OrderItem;
import com.atyx.spyx.vo.order.CartInfoVo;
import com.atyx.spyx.vo.order.OrderConfirmVo;
import com.atyx.spyx.vo.order.OrderSubmitVo;
import com.atyx.spyx.vo.order.OrderUserQueryVo;
import com.atyx.spyx.vo.product.SkuStockLockVo;
import com.atyx.spyx.vo.user.LeaderAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spyx.activity.ActivityClient;
import com.spyx.auth.AuthContextHolder;
import com.spyx.cart.CartClient;
import com.spyx.common.DateUtil;
import com.spyx.common.constant.MqConst;
import com.spyx.common.service.RabbitService;
import com.spyx.constant.RedisConst;
import com.spyx.exception.SpyxException;
import com.spyx.order.mapper.OrderItemMapper;
import com.spyx.order.mapper.OrderMapper;
import com.spyx.order.service.OrderService;
import com.spyx.product.ProductClient;
import com.spyx.result.ResultCodeEnum;
import com.spyx.user.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartClient cartClient;

    @Autowired
    private ActivityClient activityClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProductClient productClient;

    @Autowired
    private RabbitService rabbitService;

    //确认订单
    @Override
    public OrderConfirmVo confirmOrder(Long userId) {

        //1.获取团长和提货点信息-远程调用-service-user
        LeaderAddressVo leaderAddressVo = userFeignClient.getLeaderAddressVoById(userId);
        //2.得到购物车中的商品列表(被选中的商品列表)-远程调用-service-cart
        List<CartInfo> cartCheckedList = cartClient.getCartCheckedList(userId);
        //3.获取购物车中商品参加的活动和优惠券-远程调用 -service-activity
        OrderConfirmVo orderConfirmVo = activityClient.findCartActivityAndCoupon(cartCheckedList, userId);
        //4.封装OrderConfirmVo缺少的数据
        orderConfirmVo.setLeaderAddressVo(leaderAddressVo);
        //5.生成订单编号,保存到返回的对象中
        //订单编号需要保存到redis中 ，原因:防止用户重复提交订单
        String orderNo = System.currentTimeMillis()+"";//IdWorker.getTimeId();
        //redis的key order:repeat:订单编号值   value ：订单编号
        redisTemplate.opsForValue().set(RedisConst.ORDER_REPEAT + orderNo, orderNo, 24, TimeUnit.HOURS);
        orderConfirmVo.setOrderNo(orderNo);

        return orderConfirmVo;
    }

    //生成订单
    @Override
    public  Long  submitOrder(OrderSubmitVo orderSubmitVo) {
        //1.获取用户id,确认是谁的订单
        Long userId = orderSubmitVo.getUserId();
        //2.校验订单是否重复提交
        //实现方式: 使用redis+lua脚本(使用lua脚本将判断语句直接发送给redis,避免出现线程安全问题)
        //2.1 获取订单编号
        String orderNo = orderSubmitVo.getOrderNo();
        if(StringUtils.isEmpty(orderNo)){
            throw new SpyxException(ResultCodeEnum.ILLEGAL_REQUEST);//返回:非法请求
        }
        //lua脚本  KEYS[1]   ARGV[1] 类似于变量，占位符
        //2.2 拿到orderNo到redis进行查询
        //(1) 如果redis中有相同的orderNo,是正常提交订单,把redis中orderNo删除掉
        //(2)如果redis中没有相同的orderNo,表示重复提交了订单，不能继续往后执行
        String script = "if(redis.call('get', KEYS[1]) == ARGV[1]) " +
                        "then " +
                        "return redis.call('del', KEYS[1]) " +   //del 指令执行成功返回1
                        "else " +
                        "return 0 " +
                        "end";
        //使用redisTemplate执行lua脚本，设置脚本返回的类型:Boolean 0表示false  1表示true
        Boolean flag = (Boolean) redisTemplate.execute(
                        new DefaultRedisScript(script, Boolean.class),
                        Arrays.asList(RedisConst.ORDER_REPEAT+orderNo),
                        orderNo );
        if(!flag){  //flag为  表示重复提交了
            throw new SpyxException(ResultCodeEnum.REPEAT_SUBMIT);//表单重复提交
        }
        //3.验证库存并且锁定库存
        // 仓库中有10个西瓜 你买了2个
        // 校验库存:  (1) 库存足够,锁定2个西瓜-这里不是真的更新数据库  (2) 库存不够，不能生成订单
        //3.1 查看购物车中已选中的商品的库存量是否足够-
        List<CartInfo> cartCheckedList = cartClient.getCartCheckedList(userId);
        //3.2 筛选出购物车商品中，商品类型为普通的商品数据
        List<CartInfo> commonCartSkuInfoList = cartCheckedList.stream()
                .filter(cartInfo -> cartInfo.getSkuType() == SkuType.COMMON.getCode())
                .collect(Collectors.toList());
        //3.3 查询库存，锁定库存-操作的是service-product服务模块
        // 将List<CartInfo> 取出数据绑定到List<SkuStockLockVo>，原因:cartInfo中的数据太多，绑定数据只需要skuid,skunum
        if(!CollectionUtils.isEmpty(commonCartSkuInfoList)){
            //封装的是购物车中商品的skuid和购买的数量
            List<SkuStockLockVo> skuStockLockVoList = commonCartSkuInfoList.stream()
                    .map(cartInfo -> {
                        SkuStockLockVo skuStockLockVo = new SkuStockLockVo();
                        skuStockLockVo.setSkuId(cartInfo.getSkuId());
                        skuStockLockVo.setSkuNum(cartInfo.getSkuNum());
                        return skuStockLockVo;
                    }).collect(Collectors.toList());
            //3.4 远程调取服务，实现查询库存和锁定库存(由于这些数据都是在shequ-product数据库)
            Boolean checkAndLock = productClient.checkAndLock(skuStockLockVoList, orderNo);
            if(!checkAndLock){
                throw  new SpyxException(ResultCodeEnum.ORDER_STOCK_FALL);
            }

        }

        //4.生成订单
        // 4.1 保存订单数据到order_info和order_item数据表
        //参数1: 订单的相关数据  参数2:选中的商品列表
        Long orderId=this.saveOrder(orderSubmitVo,cartCheckedList);

        //4.2 下单完成后，删除redis中购物车中对应的商品数据-mq消息队列
        //(1) 导入rabbit-util模块 (2) 注入RabbitService对象 (3) 调取方法发送消息
        rabbitService.sendMessage(MqConst.EXCHANGE_ORDER_DIRECT,MqConst.ROUTING_DELETE_CART,orderSubmitVo.getUserId());

        //5.返回订单ID
        return orderId;
    }

    @Autowired
    private OrderItemMapper orderItemMapper;
    //保存订单数据到order_info和order_item数据表
    @Transactional(rollbackFor = Exception.class)
    public Long saveOrder(OrderSubmitVo orderSubmitVo, List<CartInfo> cartCheckedList) {
        //1.校验购物车商品列表
        if(CollectionUtils.isEmpty(cartCheckedList)){
            throw  new SpyxException(ResultCodeEnum.DATA_ERROR);//数据异常
        }
        //2.查询用户提货点和团长信息
        Long userId = AuthContextHolder.getUserId();
        LeaderAddressVo leaderAddressVo = userFeignClient.getLeaderAddressVoById(userId);
        if(leaderAddressVo==null){
            throw new SpyxException(ResultCodeEnum.DATA_ERROR);//数据异常
        }
        //3.计算订单中涉及的金额(营销活动金额，优惠券金额)
        //3.1 计算营销活动金额
        Map<String, BigDecimal> activitySplitAmount = this.computeActivitySplitAmount(cartCheckedList);
        //3.2 计算优惠券金额 ，说明: 优惠券id来资源OrderSubmitVo
        Map<String, BigDecimal> couponInfoSplitAmount = this.computeCouponInfoSplitAmount(cartCheckedList, orderSubmitVo.getCouponId());

        //4.封装订单项(Order_item表)的数据
        List<OrderItem> orderItemsList=new ArrayList<>();
        for (CartInfo cartInfo : cartCheckedList) {
            OrderItem orderItem = new OrderItem();
            orderItem.setCategoryId(cartInfo.getCategoryId());
           if(cartInfo.getSkuType()==SkuType.COMMON.getCode()){
                orderItem.setSkuType(SkuType.COMMON);
           }else{
               orderItem.setSkuType(SkuType.SECKILL);
           }
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setImgUrl(cartInfo.getImgUrl());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setLeaderId(orderSubmitVo.getLeaderId());
            //商品促销活动分解金额
            BigDecimal activityBigDecimal = activitySplitAmount.get("activity:" + cartInfo.getSkuId());
            if(activityBigDecimal==null) activityBigDecimal=new BigDecimal("0");
            orderItem.setSplitActivityAmount(activityBigDecimal);
            //优惠券优惠分解金额
            BigDecimal couponDecimal = couponInfoSplitAmount.get("coupon:" + cartInfo.getSkuId());
            if(couponDecimal==null) couponDecimal=new BigDecimal("0");
            orderItem.setSplitCouponAmount(couponDecimal);
            //该商品经过优惠后的分解金额(每件商品消费的总金额)
            BigDecimal skuTotalAmount = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));//优惠前
            BigDecimal splitTotalAmount = skuTotalAmount.subtract(activityBigDecimal).subtract(couponDecimal);//优惠后
            orderItem.setSplitTotalAmount(splitTotalAmount);
            orderItemsList.add(orderItem);
        }

        //5.封装订单OrderInfo表(一个订单-order_Info包含多件商品-order_item)
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(orderSubmitVo.getUserId());
        orderInfo.setOrderNo(orderSubmitVo.getOrderNo());
        orderInfo.setOrderStatus(OrderStatus.UNPAID); //订单状态，生成成功未支付
        orderInfo.setLeaderId(orderSubmitVo.getLeaderId());//团长id
        orderInfo.setLeaderName(leaderAddressVo.getLeaderName());//团长名称

        orderInfo.setLeaderPhone(leaderAddressVo.getLeaderPhone());
        orderInfo.setTakeName(leaderAddressVo.getTakeName());
        orderInfo.setReceiverName(orderSubmitVo.getReceiverName());//收货人姓名
        orderInfo.setReceiverPhone(orderSubmitVo.getReceiverPhone());//收货人电话
        orderInfo.setReceiverProvince(leaderAddressVo.getProvince());
        orderInfo.setReceiverCity(leaderAddressVo.getCity());
        orderInfo.setReceiverDistrict(leaderAddressVo.getDistrict());
        orderInfo.setReceiverAddress(leaderAddressVo.getDetailAddress());
        orderInfo.setWareId(cartCheckedList.get(0).getWareId());
        orderInfo.setProcessStatus(ProcessStatus.UNPAID); //订单进度
        //设置订单相关的金额(总金额，活动金额，优惠券金额等)
        // 活动的总金额
        BigDecimal activityTotalDecimal = activitySplitAmount.get("activity:total");
        if(activityTotalDecimal==null) activityTotalDecimal=new BigDecimal("0");
        //优惠券总金额
        BigDecimal couponTotalDecimal = couponInfoSplitAmount.get("coupon:total");
        if(couponTotalDecimal==null) couponTotalDecimal=new BigDecimal("0");
        //订单消费原价总金额
        BigDecimal original_total_amount = this.computeTotalAmount(cartCheckedList);
        if(original_total_amount==null) original_total_amount=new BigDecimal("0");
        //实际消费金额
        BigDecimal total_amount = original_total_amount.subtract(activityTotalDecimal).subtract(couponTotalDecimal);
        orderInfo.setActivityAmount(activityTotalDecimal);
        orderInfo.setCouponAmount(couponTotalDecimal);
        orderInfo.setOriginalTotalAmount(original_total_amount);
        orderInfo.setTotalAmount(total_amount);
        //团长佣金
        BigDecimal profitRate = new BigDecimal("0");//比例
        BigDecimal commission_amount = orderInfo.getTotalAmount().multiply(profitRate);
        orderInfo.setCommissionAmount(commission_amount);
        //6.添加到数据 -order_Info
        baseMapper.insert(orderInfo);
        //7.添加订单详情表:order_item表
        for (OrderItem orderItem : orderItemsList) {
            orderItem.setOrderId(orderInfo.getId());
            //新增数据
            orderItemMapper.insert(orderItem);
        }
        //8.如果当前订单中使用了优惠券，更新优惠券状态
        if(orderInfo.getCouponId()!=null){ //说明订单中使用到了优惠券
            //远程调用service-activity模块，更新优惠券状态
            activityClient.updateCouponInfoUseStatus(orderSubmitVo.getUserId(),
                    orderSubmitVo.getCouponId(),orderInfo.getId());
        }
        //9.下单成功，在redis中记录用户购物的商品数量
        //9.1 创建redis的key=order:sku:userId
        String orderSkuKey=RedisConst.ORDER_SKU_MAP+orderSubmitVo.getUserId();
        //9.2 将订单中的商品数量保存到redis中-hash类型(等价于map套map)
        // order:sku:1001    1-10    2-3   1,2表示商品iD   10,3表示购买数量
        // String-orderSkuKey   String -商品id  Integer-购买的数量
        BoundHashOperations<String,String,Integer> hashOps = redisTemplate.boundHashOps(orderSkuKey);
        //9.3 将购物车中购买的商品数据保存到该redis中
        for (CartInfo cartInfo : cartCheckedList) {
            //先从redis中获取指定商品的购买数量
            Boolean bool = hashOps.hasKey(cartInfo.getSkuId().toString());
            if(bool){
                //取出原来的商品数量进行叠加
                Integer oldskuNum = hashOps.get(cartInfo.getSkuId().toString());
                Integer newSkunum=oldskuNum+cartInfo.getSkuNum();
                hashOps.put(cartInfo.getSkuId().toString(),newSkunum);
            }
        }
        //9.4 设置过期时间
        redisTemplate.expire(orderSkuKey, DateUtil.getCurrentExpireTimes(),TimeUnit.SECONDS);

        //10.返回订单id
        return  orderInfo.getId();
    }

    //计算总金额
    private BigDecimal computeTotalAmount(List<CartInfo> cartInfoList) {
        BigDecimal total = new BigDecimal(0);
        for (CartInfo cartInfo : cartInfoList) {
            BigDecimal itemTotal = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
            total = total.add(itemTotal);
        }
        return total;
    }

    /**
     * 计算购物项分摊的优惠减少金额
     * 打折：按折扣分担
     * 现金：按比例分摊
     * @param cartInfoParamList
     * @return
     */
    private Map<String, BigDecimal> computeActivitySplitAmount(List<CartInfo> cartInfoParamList) {
        Map<String, BigDecimal> activitySplitAmountMap = new HashMap<>();

        //活动活动相关信息
        List<CartInfoVo> cartInfoVoList = activityClient.findCartActivityList(cartInfoParamList);

        //活动总金额
        BigDecimal activityReduceAmount = new BigDecimal(0);
        if(!CollectionUtils.isEmpty(cartInfoVoList)) {
            for(CartInfoVo cartInfoVo : cartInfoVoList) {
                ActivityRule activityRule = cartInfoVo.getActivityRule();
                List<CartInfo> cartInfoList = cartInfoVo.getCartInfoList();
                if(null != activityRule) {
                    //优惠金额， 按比例分摊
                    BigDecimal reduceAmount = activityRule.getReduceAmount();
                    activityReduceAmount = activityReduceAmount.add(reduceAmount);
                    if(cartInfoList.size() == 1) {
                        activitySplitAmountMap.put("activity:"+cartInfoList.get(0).getSkuId(), reduceAmount);
                    } else {
                        //总金额
                        BigDecimal originalTotalAmount = new BigDecimal(0);
                        for(CartInfo cartInfo : cartInfoList) {
                            BigDecimal skuTotalAmount = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
                            originalTotalAmount = originalTotalAmount.add(skuTotalAmount);
                        }
                        //记录除最后一项是所有分摊金额， 最后一项=总的 - skuPartReduceAmount
                        BigDecimal skuPartReduceAmount = new BigDecimal(0);
                        if (activityRule.getActivityType() == ActivityType.FULL_REDUCTION) {
                            for(int i=0, len=cartInfoList.size(); i<len; i++) {
                                CartInfo cartInfo = cartInfoList.get(i);
                                if(i < len -1) {
                                    BigDecimal skuTotalAmount = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
                                    //sku分摊金额
                                    BigDecimal skuReduceAmount = skuTotalAmount.divide(originalTotalAmount, 2, RoundingMode.HALF_UP).multiply(reduceAmount);
                                    activitySplitAmountMap.put("activity:"+cartInfo.getSkuId(), skuReduceAmount);

                                    skuPartReduceAmount = skuPartReduceAmount.add(skuReduceAmount);
                                } else {
                                    BigDecimal skuReduceAmount = reduceAmount.subtract(skuPartReduceAmount);
                                    activitySplitAmountMap.put("activity:"+cartInfo.getSkuId(), skuReduceAmount);
                                }
                            }
                        } else {
                            for(int i=0, len=cartInfoList.size(); i<len; i++) {
                                CartInfo cartInfo = cartInfoList.get(i);
                                if(i < len -1) {
                                    BigDecimal skuTotalAmount = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));

                                    //sku分摊金额
                                    BigDecimal skuDiscountTotalAmount = skuTotalAmount.multiply(activityRule.getBenefitDiscount().divide(new BigDecimal("10")));
                                    BigDecimal skuReduceAmount = skuTotalAmount.subtract(skuDiscountTotalAmount);
                                    activitySplitAmountMap.put("activity:"+cartInfo.getSkuId(), skuReduceAmount);

                                    skuPartReduceAmount = skuPartReduceAmount.add(skuReduceAmount);
                                } else {
                                    BigDecimal skuReduceAmount = reduceAmount.subtract(skuPartReduceAmount);
                                    activitySplitAmountMap.put("activity:"+cartInfo.getSkuId(), skuReduceAmount);
                                }
                            }
                        }
                    }
                }
            }
        }
        activitySplitAmountMap.put("activity:total", activityReduceAmount);
        return activitySplitAmountMap;
    }

    //优惠券优惠金额
    private Map<String, BigDecimal> computeCouponInfoSplitAmount(List<CartInfo> cartInfoList, Long couponId) {
        Map<String, BigDecimal> couponInfoSplitAmountMap = new HashMap<>();

        if(null == couponId) return couponInfoSplitAmountMap;
        //查询某张优惠券使用的商品范围
        CouponInfo couponInfo = activityClient.findRangeSkuIdList(cartInfoList, couponId);

        if(null != couponInfo) {
            //sku对应的订单明细
            Map<Long, CartInfo> skuIdToCartInfoMap = new HashMap<>();
            for (CartInfo cartInfo : cartInfoList) {
                skuIdToCartInfoMap.put(cartInfo.getSkuId(), cartInfo);
            }
            //优惠券对应的skuId列表
            List<Long> skuIdList = couponInfo.getSkuIdList();
            if(CollectionUtils.isEmpty(skuIdList)) {
                return couponInfoSplitAmountMap;
            }
            //优惠券优化总金额
            BigDecimal reduceAmount = couponInfo.getAmount();
            if(skuIdList.size() == 1) {
                //sku的优化金额
                couponInfoSplitAmountMap.put("coupon:"+skuIdToCartInfoMap.get(skuIdList.get(0)).getSkuId(), reduceAmount);
            } else {
                //总金额
                BigDecimal originalTotalAmount = new BigDecimal(0);
                for (Long skuId : skuIdList) {
                    CartInfo cartInfo = skuIdToCartInfoMap.get(skuId);
                    BigDecimal skuTotalAmount = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
                    originalTotalAmount = originalTotalAmount.add(skuTotalAmount);
                }
                //记录除最后一项是所有分摊金额， 最后一项=总的 - skuPartReduceAmount
                BigDecimal skuPartReduceAmount = new BigDecimal(0);
                if (couponInfo.getCouponType() == CouponType.CASH || couponInfo.getCouponType() == CouponType.FULL_REDUCTION) {
                    for(int i=0, len=skuIdList.size(); i<len; i++) {
                        CartInfo cartInfo = skuIdToCartInfoMap.get(skuIdList.get(i));
                        if(i < len -1) {
                            BigDecimal skuTotalAmount = cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum()));
                            //sku分摊金额
                            BigDecimal skuReduceAmount = skuTotalAmount.divide(originalTotalAmount, 2, RoundingMode.HALF_UP).multiply(reduceAmount);
                            couponInfoSplitAmountMap.put("coupon:"+cartInfo.getSkuId(), skuReduceAmount);

                            skuPartReduceAmount = skuPartReduceAmount.add(skuReduceAmount);
                        } else {
                            BigDecimal skuReduceAmount = reduceAmount.subtract(skuPartReduceAmount);
                            couponInfoSplitAmountMap.put("coupon:"+cartInfo.getSkuId(), skuReduceAmount);
                        }
                    }
                }
            }
            couponInfoSplitAmountMap.put("coupon:total", couponInfo.getAmount());
        }
        return couponInfoSplitAmountMap;
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        //1.先获取order_info表中的数据
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //2.根据订单iD,查询订单详情表: order_item
        LambdaQueryWrapper<OrderItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderItem::getOrderId,orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(wrapper);
        //3.将订单详情数据封装到OrderInfo
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        //1.构建条件
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo,orderNo);
        //2.查询
        OrderInfo orderInfo = baseMapper.selectOne(wrapper);
        return orderInfo;
    }

    @Override
    public void updateOrderStatus(String orderNo) {

        //1.构建查询条件
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo,orderNo);
        //2.先查询出订单的数据
        OrderInfo orderInfo = baseMapper.selectOne(wrapper);
        //3.更新订单的支付状态
        orderInfo.setOrderStatus(OrderStatus.WAITING_DELEVER);
        //4.更新到数据库
        baseMapper.updateById(orderInfo);
    }

    @Override
    public IPage<OrderInfo> findUserOrderPage(Page page1, OrderUserQueryVo queryVo) {
        //1.查询订单信息-orderInfo表
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getUserId,queryVo.getUserId());
        wrapper.eq(OrderInfo::getOrderStatus,queryVo.getOrderStatus());
        Page orderInfoPage = baseMapper.selectPage(page1, wrapper);
        //2.遍历订单信息，查看每个订单中的详情
        List<OrderInfo> records = orderInfoPage.getRecords();
        for (OrderInfo orderInfo : records) {
            //2.1查询订单详情表: Order_item表
            LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderItem::getOrderId,orderInfo.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);
            //2.2 将查询出的订单详情列表封装到OrderInfo中
            orderInfo.setOrderItemList(orderItemList);
            //2.3 封装订单状态名称
            orderInfo.getParam().put("orderStatusName",orderInfo.getOrderStatus().getComment());
        }
        //3.返回数据
        return orderInfoPage;
    }
}
